import { Button, Input, InputNumber, Message, Radio, Select, Tabs } from '@arco-design/web-react';
import TabPane from '@arco-design/web-react/es/Tabs/tab-pane';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { ValidateRule } from '../../../types';
import DetailItem from '../../../components/detailItem';
import DetailModal from '../../../components/detailModal';
import { confirmDialog } from '../../../components/dialog';
import LoadingMask from '../../../components/loadingMask';
import { clearRepeat, formatNumber, validateField } from '../../../utils/utils';
import { apiGetCardPackDetailListByCard, apiGetCardPackDetailListByCardId,apiBuyPackOrder, apiPreOrder,apiGetCouponListByCardPackDetailId, apiPreUpdatePack, apiUpdatePack } from './api';
import { CardPackDetail } from '../packInfo/types';
import { CardPackOrder } from './types';
import { PayCouponCardUser } from '../../../types';

interface Props {
  cardId: number;
  iccid: string;
  onCancel: (update?: boolean) => void;
}

type Option = { label: string; value: number; isBasePackage: boolean; salePrice: string };
type couponOption = { label: string; value: number; reduceAmount: string; isOverlay: boolean };

const dateTypeOptions = [
  { label: '本期', value: 'now' },
  { label: '下期', value: 'next' },
];

const rule: ValidateRule = {
  cardPackDetailId: { required: true, message: '套餐必填' },
  dateType: { required: true, message: '时间类型必填' },
  walletType: { required: true, message: '付款方式必填' },
  packCount: { required: true, number: true, min: 1, message: '套餐数量不能小于1' },
};

interface UpdatePackData {
  cardId: string;
  packDetailId: string;
  packDetailName: string;
  packTimeType: string;
  /** 剩余期数（基础套餐） */
  basicPackageLeftPeriodNum: number;
  /** 加油包数量 */
  fuelPackageLeftPeriodNum: number;
  /** 剩余期数价值（基础套餐 + 加油包 + 超量订购） tips全显示 */
  leftPeriodValue: number;
  /** 套餐差额 */
  upgradeValue: number;
  /** 用户余额 */
  userBalance: number;
  /** 操作结果 */
  changeResult: boolean;
  /** 操作结果提示 有结果就显示 没有不显示 */
  changeResultMsg: string;
  /** 可选套餐和时间类型 */
  cardPreviewUpgradePackDetailItems: Array<{
    packTimeType: string;
    cardPackDetail: CardPackDetail;
  }>;
  cardPackOrderDetail?: CardPackOrder;
}

export default function BuyPackDetailDialog({ cardId, iccid, onCancel }: Props) {
  // 套餐列表
  const [packDetailList, setPackDetailList] = useState<Option[]>([]);
  // 通用套餐列表
  const [packList, setPackList] = useState<Option[]>([]);
  // 可用优惠券列表
  const [couponList, setCouponList] = useState<couponOption[]>([]);
  // 时间类型 本期 下期
  const [dateType, setDateType] = useState('now');
  // 支付钱包 部门钱包 用户钱包
  const [walletType, setWalletType] = useState<string>('card');
  // 已选套餐包
  const [cardPackDetailId, setCardPackDetailId] = useState<number>();
  // 套餐包数量  最少1个
  const [packCount, setPackCount] = useState(1);
  // 已选套餐是否是基础包
  const [isBasePackage, setIsBasePackage] = useState(false);
  // 已选优惠券id
  const [couponIds, setCouponIds] = useState<Array<number>>([]);
  // 订单预览信息
  const [orderInfo, setOrderInfo] = useState<any>();
  //错误校验
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});
  const [activeTab, setActiveTab] = useState('1');
  // 套餐升级预览数据
  const [preUpdatePack, setPreUpdatePack] = useState<UpdatePackData>();
  // 套餐升级 升级类型
  const [updatePackType, setUpdatePackType] = useState('1');
  // 套餐升级 时间类型
  const [updatePackTimeType, setUpdatePackTimeType] = useState('');
  // 已选升级套餐ID
  const [updatePackDetailId, setUpdatePackDetailId] = useState('');
  // 升级套餐 错误提示
  const [updatePackError, setUpdatePackError] = useState('');
  useEffect(() => {
    loadList();
    packDetailListFn();
  }, []); //eslint-disable-line

  useEffect(() => {
    if (activeTab === '3') {
      preUpdatePackFn();
    }
  }, [activeTab, updatePackType, updatePackTimeType, updatePackDetailId]); // eslint-disable-line

  // 获取套餐详情列表
  async function loadList() {
    try {
      let res = await apiGetCardPackDetailListByCardId(1, 1000, { cardId });
      let data = res.data;
      if (data.code === 200) {
        let _list = data.data.map((i: CardPackDetail) => ({
          label: i.name,
          value: i.id,
          salePrice: i.salePrice,
          isBasePackage: i.packageType === 'basicpackage',
        }));
        setPackDetailList(_list);
      } else {
        setPackDetailList([]);
        Message.warning(data.msg ?? '获取套餐列表失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取套餐列表失败');
    }
  }
  // 获取通用套餐列表
  async function packDetailListFn() {
    try {
      let res = await apiGetCardPackDetailListByCard(1, 1000, { useType: 'general' });
      let data = res.data;
      if (data.code === 200) {
        let _list =
          data.rows &&
          data.rows.map((i: CardPackDetail) => ({
            label: i.name,
            value: i.id,
            salePrice: i.salePrice,
            isBasePackage: i.packageType === 'basicpackage',
          }));
        setPackList(_list);
      } else {
        setPackList([]);
        Message.warning(data.msg ?? '获取套餐列表失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取套餐列表失败');
    }
  }
  // 获取可用优惠券列表
  async function couponListByCardPackDetailList(cardPackDetailId: number) {
    try {
      let res = await apiGetCouponListByCardPackDetailId(cardId, cardPackDetailId, packCount);
      let data = res.data;
      if (data.code === 200) {
        let _list = data.data.map((i: PayCouponCardUser) => ({
          label: i.couponName + '-' + (i.isOverlay === 'Y' ? '可叠加' : '不可叠加'),
          value: i.id,
          reduceAmount: i.reduceAmount,
          isOverlay: i.isOverlay === 'Y',
        }));
        setCouponList(_list);
        setCouponIds([]);
      } else {
        setCouponList([]);
        Message.warning(data.msg ?? '获取套餐列表失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '获取可用套餐列表失败');
    }
  }

  // 选择优惠券
  function handleSelectCoupon(values: number[]) {
    if (!values.length) {
      setCouponIds([]);
      return;
    }
    let v: number = values.pop()!;
    // 如果新选了叠加，就把之前的不是叠加的全去掉、
    // 如果新选了不叠加，就只保留不叠加的
    let _tmp: Array<number> = [];
    let coupon = couponList.find((i) => i.value === v);
    /// 先处理不叠加的 只保留最新的
    if (!coupon?.isOverlay) {
      _tmp = [v];
    } else {
      // 再处理叠加的
      for (let i of couponList) {
        // 如果是已选中的优惠券 并且是叠加的，则还放到选中组
        if (values.includes(i.value) && i.isOverlay) {
          _tmp.push(i.value);
        }
      }
      // 保留完所有叠加的之后再把 自己放进去
      _tmp.push(v);
    }
    setCouponIds(_tmp);
  }

  useEffect(() => {
    if (cardPackDetailId) {
      preOrder();
    }
  }, [cardPackDetailId, couponIds, dateType, walletType, packCount]); // eslint-disable-line

  // 预下单
  async function preOrder() {
    try {
      let res = await apiPreOrder(cardPackDetailId!, cardId, couponIds, packCount);
      let data = res.data;
      if (data.code === 200) {
        setOrderInfo(data.data);
      } else {
        setOrderInfo(null);
        Message.warning(data.msg ?? '预下单失败');
      }
    } catch (e: any) {
      setOrderInfo(null);
      Message.error(e.message ?? '预下单失败');
    }
  }

  async function handleConfirm() {
    if (activeTab === '3') {
      if (!updatePackDetailId) {
        return Message.warning('请选择升级套餐');
      }
      if (updatePackError) {
        return Message.warning(updatePackError);
      }
      let modalRes = await confirmDialog({ title: '提示', content: '是否确认升级？' });
      if (!modalRes) return;
      try {
        LoadingMask.show('正在升级...');
        let res = await apiUpdatePack(cardId, updatePackType, updatePackDetailId);
        let data = res.data;
        if (data.code === 200) {
          Message.success('升级成功');
          onCancel(true);
        } else {
          Message.warning(data.msg ?? '升级失败');
        }
      } catch (e: any) {
        Message.error(e.message ?? '购买失败');
      } finally {
        LoadingMask.hide();
        return;
      }
    }
    if (!orderInfo) {
      return Message.warning('预下单已失败，当前不能购买');
    }
    let validate = validateField({ cardPackDetailId, dateType, walletType, packCount }, rule);
    setErrorData(validate);
    if (Object.keys(validate).length) return;

    try {
      LoadingMask.show('正在购买...');
      let res = await apiBuyPackOrder({
        cardId,
        cardPackDetailId,
        dateType,
        walletType,
        couponCodeIds: couponIds,
        number: packCount ?? 1,
      });
      let data = res.data;
      if (data.code === 200) {
        Message.success('购买成功');
        onCancel(true);
      } else {
        Message.warning(data.msg ?? '购买失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '购买失败');
    } finally {
      LoadingMask.hide();
    }
  }
  // 预览升级套餐
  async function preUpdatePackFn() {
    try {
      LoadingMask.show('正在预览...');
      let res = await apiPreUpdatePack(cardId, updatePackType, updatePackDetailId);
      let data = res.data;
      if (data.code === 200) {
        let _data: UpdatePackData = data.data;
        setPreUpdatePack(_data);
        let updatePackTimeTypes: string[] = clearRepeat(
          (_data?.cardPreviewUpgradePackDetailItems ?? []).map((i) => i.packTimeType)
        ) as string[];
        // let _type = updatePackTimeType|| updatePackTimeTypes[0];
        if (!updatePackTimeTypes.length) {
          setUpdatePackTimeType('');
          setUpdatePackDetailId('');
        } else if (!updatePackTimeTypes.includes(updatePackTimeType)) {
          setUpdatePackTimeType(updatePackTimeTypes[0]);
          setUpdatePackDetailId(
            (_data?.cardPreviewUpgradePackDetailItems ?? [])
              .find((i) => i.packTimeType === updatePackTimeTypes[0])
              ?.cardPackDetail?.id?.toString() ?? ''
          );
        } else if (!updatePackDetailId) {
          setUpdatePackDetailId(
            (_data?.cardPreviewUpgradePackDetailItems ?? [])
              .find((i) => i.packTimeType === updatePackTimeType)
              ?.cardPackDetail?.id?.toString() ?? ''
          );
        }
        setUpdatePackError(!_data.changeResult ? _data.changeResultMsg : '');
      } else {
        setUpdatePackError(data.msg ?? '预下单失败');
      }
    } catch (e: any) {
      setUpdatePackError(e.message ?? '预览失败');
    } finally {
      LoadingMask.hide();
    }
  }

  let updatePackTimeTypes: string[] = clearRepeat(
    (preUpdatePack?.cardPreviewUpgradePackDetailItems ?? []).map((i) => i.packTimeType)
  ) as string[];

  let updatePacks = (preUpdatePack?.cardPreviewUpgradePackDetailItems ?? [])
    .filter((i) => i.packTimeType === updatePackTimeType)
    .map((i) => ({
      label: `${i.cardPackDetail!.name!}${
        (i.cardPackDetail.monthNum ?? 0) > 1
          ? `/月均${formatNumber((i.cardPackDetail.salePrice ?? 0) / (i.cardPackDetail?.monthNum ?? 0))}`
          : ''
      }/总价¥${formatNumber(i.cardPackDetail!.salePrice)}`,
      value: i.cardPackDetail!.id!.toString(),
    }));

  return (
    <DetailModal
      className="w-700"
      title={`手动订购【${iccid}】`}
      show
      onCancel={() => onCancel()}
      onConfirm={handleConfirm}
    >
      <Tabs
        key="card"
        className="tab-card mb-20"
        onChange={(v) => {
          setActiveTab(v);
          setCardPackDetailId(undefined);
          setOrderInfo(undefined);
          setCouponIds([]);
        }}
      >
        <TabPane key="1" title="购买套餐"></TabPane>
        
          <TabPane key="2" title="通用套餐"></TabPane>
        
       
          <TabPane key="3" title="升级套餐"></TabPane>
       
      </Tabs>
      {activeTab !== '3' && (
        <DetailItem
          label="选择套餐"
          required
          labelSpan={4}
          outlet={4}
          tips={orderInfo?.packDetailContent}
          error={errorData?.cardPackDetailId}
        >
          {activeTab === '1' ? (
            //购买套餐
            <Select
              className="m-select"
              showSearch
              filterOption={(inputValue, option) =>
                option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
                option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
              }
              options={packDetailList}
              value={cardPackDetailId}
              onChange={(v) => {
                setCardPackDetailId(v);
                couponListByCardPackDetailList(v);
                let _tmp = packDetailList.find((i) => i.value === v);
                setIsBasePackage(_tmp!.isBasePackage);
                if (!_tmp!.isBasePackage) {
                  setDateType('now');
                }
              }}
            />
          ) : (
            // 通用套餐
            <Select
              className="m-select"
              showSearch
              filterOption={(inputValue, option) =>
                option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
                option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
              }
              options={packList}
              value={cardPackDetailId}
              onChange={(v) => {
                setCardPackDetailId(v);
                let _tmp = packList.find((i) => i.value === v);
                setIsBasePackage(_tmp!.isBasePackage);
                if (!_tmp!.isBasePackage) {
                  setDateType('now');
                }
              }}
            />
          )}
        </DetailItem>
      )}
      {activeTab !== '3' && (
        <DetailItem label="套餐数量" labelSpan={4} outlet={4} error={errorData?.packCount}>
          <InputNumber className="m-input" min={1} value={packCount} onChange={(v) => setPackCount(v)} />
        </DetailItem>
      )}
      {activeTab === '1' && (
        <div className="bw-100">
          <DetailItem label="可用优惠券" labelSpan={4} outlet={4} error={errorData?.reduceAmount}>
            <Select
              showSearch
              filterOption={(inputValue, option) =>
                option.props.value.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0 ||
                option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
              }
              allowClear
              mode="multiple"
              className="m-select"
              options={couponList}
              value={couponIds}
              onChange={handleSelectCoupon}
            />
          </DetailItem>
          <div className="d-flex-r">
            <DetailItem label="套餐价格" labelSpan={8} outlet={2}>
              <Input className="m-input after" value={orderInfo?.salePrice} disabled />
            </DetailItem>
            <DetailItem label="抵扣金额" labelSpan={8} outlet={2}>
              <Input className="m-input after" value={orderInfo?.couponPrice} disabled />
            </DetailItem>
          </div>
          <DetailItem label="实付" labelSpan={4} outlet={4}>
            <Input className="m-input after" value={orderInfo?.realPrice} disabled />
          </DetailItem>
        </div>
      )}
      {activeTab !== '3' && (
        <DetailItem
          label="时间类型"
          required
          labelSpan={4}
          outlet={4}
          tips="*下期套餐生效时间自动往后顺延"
          error={errorData?.cardPackDetailId}
        >
          <Radio.Group
            options={dateTypeOptions}
            disabled={!isBasePackage}
            value={dateType}
            onChange={(v) => setDateType(v)}
          />
        </DetailItem>
      )}
      {activeTab !== '3' && (
        <DetailItem label="钱包类型" required labelSpan={4} outlet={4} error={errorData?.cardPackDetailId}>
          <Radio.Group defaultValue={walletType}>
          
              <Radio
                value="dept"
                onChange={(v) => {
                  setWalletType('dept');
                  setCouponIds([]);
                }}
              >
                代理付钱
              </Radio>
            
           
              <Radio
                value="card"
                onChange={(v) => {
                  setWalletType('card');
                }}
              >
                本卡余额支付
              </Radio>
           
          </Radio.Group>
        </DetailItem>
      )}
      {activeTab === '3' && (
        <div className="bw-100">
          <div className="d-flex-r">
            <DetailItem label="当前套餐" labelSpan={8} outlet={2}>
              <Input className="m-input" value={preUpdatePack?.packDetailName} disabled />
            </DetailItem>
            <DetailItem label="时间类型" labelSpan={8} outlet={2}>
              <Input className="m-input" value={preUpdatePack?.packTimeType} disabled />
            </DetailItem>
          </div>
          <div className="d-flex-r">
            <DetailItem label="当前有效期" labelSpan={8} outlet={2}>
              <Input
                className="m-input"
                value={
                  dayjs(preUpdatePack?.cardPackOrderDetail?.startEffectTime).format('YYYY/MM/DD') +
                  '-' +
                  dayjs(preUpdatePack?.cardPackOrderDetail?.endEffectTime).format('YYYY/MM/DD')
                }
                disabled
              />
            </DetailItem>
            <DetailItem label="套餐售价" labelSpan={16} outlet={1}>
              <Input className="m-input" value={preUpdatePack?.cardPackOrderDetail?.salePrice} disabled />
            </DetailItem>
            <DetailItem label="月均价格" labelSpan={16} outlet={1}>
              <InputNumber
                className="m-input"
                value={formatNumber(
                  parseFloat((preUpdatePack?.cardPackOrderDetail?.realPrice ?? 0).toString()) /
                    (preUpdatePack?.cardPackOrderDetail?.totalPhases ?? 0)
                )}
                disabled
              />
            </DetailItem>
          </div>
          <DetailItem label="升级类型" labelSpan={4} outlet={4}>
            <Radio.Group
              value={updatePackType}
              options={[
                { label: '升级流量', value: '1' },
                { label: '延长期限', value: '2' },
              ]}
              onChange={(v) => setUpdatePackType(v)}
            />
          </DetailItem>
          <DetailItem label="选择套餐" labelSpan={4} outlet={4}>
            <div>
              {
                <div className="d-flex-r flex-wrap mb-20">
                  {updatePackTimeTypes.map((i) => (
                    <Button
                      key={i}
                      className="mr-10 mb-10"
                      onClick={() => setUpdatePackTimeType(i)}
                      type={i === updatePackTimeType ? 'primary' : 'secondary'}
                    >
                      {i}
                    </Button>
                  ))}
                </div>
              }

              <div>选择套餐</div>
              <div className="d-flex-r flex-wrap">
                {updatePacks.map((i) => (
                  <Button
                    key={i.value}
                    className="mr-10 mb-10"
                    type={i.value === updatePackDetailId ? 'primary' : 'secondary'}
                    onClick={() => setUpdatePackDetailId(i.value)}
                  >
                    {i.label}
                  </Button>
                ))}
              </div>
            </div>
          </DetailItem>
          <div className="d-flex-r">
            <DetailItem label="套餐剩余期数" labelSpan={16}>
              <InputNumber className="m-input" value={preUpdatePack?.basicPackageLeftPeriodNum} disabled />
            </DetailItem>
            <DetailItem label="加油包数量" labelSpan={16}>
              <InputNumber className="m-input" value={preUpdatePack?.fuelPackageLeftPeriodNum} disabled />
            </DetailItem>
            <DetailItem label="剩余期数价值" labelSpan={8} tips="（基础套餐 + 加油包 + 超量订购）" outlet={2}>
              <InputNumber className="m-input" value={preUpdatePack?.leftPeriodValue} disabled />
            </DetailItem>
          </div>
          <div className="d-flex-r">
            <DetailItem label="升级所需金额" labelSpan={8} outlet={2}>
              <InputNumber className="m-input" value={preUpdatePack?.upgradeValue} disabled />
            </DetailItem>
            <DetailItem label="用户余额" labelSpan={8} outlet={2}>
              <InputNumber className="m-input" value={preUpdatePack?.userBalance} disabled />
            </DetailItem>
          </div>
          <div className="text-red-color">{updatePackError}</div>
        </div>
      )}
    </DetailModal>
  );
}
